﻿<?php
define('IN_ECS', true);
require('../../includes/init.php');
include_once('../../includes/lib_common.php');
include_once('../../includes/lib_transaction.php');
include_once('../../includes/lib_passport.php');

require_once 'requires.php';
$config->CALLBACK = $callbackurl_flow; 

//获取返回CODE
$code = $_GET['code'];
//echo $code, '<br/><br/>';
if ($_GET['error']=='login_denied'){
	echo "<script>window.close();</script> ";
	exit;
	}



//获取AccessToken
$oauth = new RenRenOauth();
/**
 * 返回以下格式的数组
 *array(
 *	'access_token' => '130705|5.a2bf7f751cc195cbb310ff15e3cd793a.86400.1305525600-223378553',
 *	'expires_in' => 87048,
 *);
 */
$token = $oauth->getAccessToken($code);
//var_dump($token);
//echo '<br/><br/>';




//获取Session Key
$oauth = new RenRenOauth();
$access_token = $token['access_token'];
$key = $oauth->getSessionKey($access_token);
//var_dump($key);
//echo '<br/><br/>';



# api调用时实例化RenRenClient对象，oauth授权时实例化RenRenOauth对象。
$client = new RenRenClient();
$session_key = $key['session_key'];
$uid = $key['user']['id'];
$client->setSessionKey($session_key);

# $client->setCallId('12345678');

# 调用api时的第一个参数是api方法名。
# 第二个参数请参考config.inc.php文件中的配置进行设置。
$userinfo = $client->POST('users.getInfo', array($uid, 'name'));
//var_dump($userinfo);
//echo '<br/><br/>';

				$username='renren'.$userinfo[0]["uid"];
				$password=time();//随机密码
				$email='@renren.com';//邮箱
				$renrenname=trim($userinfo[0]['name']);//人人网姓名
			 /* 检测用户名 */
					function check_user($username){
					$sql = "SELECT user_id FROM " . $GLOBALS['ecs']->table("users"). " WHERE user_name='$username'";
					$row = $GLOBALS['db']->getRow($sql);
					if (!empty($row)){ return true; }else{return false;}
					}
			 if (check_user($username)!==false){//账号存在直接完成登录
					$GLOBALS['user']->set_session($username);
					$GLOBALS['user']->set_cookie($username);
					//header("Location: user.php\n");
					update_user_info();
					recalculate_price();
					echo "<script>window.opener.location='/flow.php?step=checkout';</script> ";
					echo "<script>window.close();</script> ";
					exit;
			 }
			 else
			 {//账号不存在就完成注册并自动登录
					$reg_date = time();
					$password =md5($password);
					$GLOBALS['db']->query('INSERT INTO ' . $GLOBALS['ecs']->table("users") . "(`email`, `user_name`, `password`, `reg_time`, `last_login`, `last_ip`, `msn`) VALUES ('$email', '$username', '$password', '$reg_date', '$reg_date', '$ip', '$renrenname')");//账号不存在 就写入数据库 并登陆
					$GLOBALS['user']->set_session($username);
					$GLOBALS['user']->set_cookie($username);
					update_user_info();
					recalculate_price();
					//header("Location: user.php\n");
					echo "<script>window.opener.location='/flow.php?step=checkout';</script> ";
					echo "<script>window.close();</script> ";		
					exit;
			 }

?>